<template>
  <div>
    <div>
      <span>已选：{{selectedDetails.length}}</span>
      <el-button size="mini" type="primary" style="margin-left: 12px" @click="confirmSelectData">确定</el-button>
    </div>
    <el-col :span="24" class="action-bar">
      <el-input clearable @clear="inputClear" placeholder="商品名称/所属门店/UPC码" style="width:220px;margin-right: 8px" v-model="searchText"></el-input>

      <!--<el-select style="margin-left: 10px" @change="searchData" @clear="merchantSelectClear" clearable v-model="merchantId" placeholder="所属门店">
        <el-option v-for="item in merchantList" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>-->

      <el-select style="margin-left: 10px" @change="searchData" @clear="classifySelectClear" clearable v-model="classifyId" :placeholder="'商品分类'">
        <el-option v-for="item in classifyList" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>

      <el-select v-if="classifyId" style="margin-left: 10px" @change="searchData" @clear="selectClear" clearable v-model="childClassifyId" placeholder="选择子分类">
        <el-option v-for="item in classifyListSecond" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>

      <el-button type="primary" size="medium" style="margin-left:10px;" @click="searchData">检索</el-button>
      <el-button size="medium" style="margin-left:20px;" @click="resetSearch">重置</el-button>
    </el-col>
    <el-table ref="dataList" stripe :data="tableData" v-loading="tableLoadingShow" element-loading-text="加载中"
              style="width: 100%;margin-top: 10px;" class="el_table_style"
              :header-cell-style="{background:'#eef1f6',color:'#606266',height: '50px'}"
              @select="handleSelect" @select-all="handleSelectionAll">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="商品ID" prop="id"></el-table-column>
      <el-table-column label="UPC码" prop="upc"></el-table-column>
      <el-table-column label="封面图">
        <template slot-scope="scope">
          <div>
            <img :src="scope.row.thumb_url" alt="" style="width:50px;height:50px;object-fit:cover;margin-right: 15px">
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="name"></el-table-column>
      <el-table-column label="商品类型" prop="goods_type_name"></el-table-column>
    </el-table>

    <div class="page-code">
      <el-pagination
        background :current-page="page" :page-size="limit" layout="prev, pager, next" :total="pageTotal" @current-change="pageChange">
      </el-pagination>
    </div>

  </div>
</template>

<script>
  export default {
    props: {
      componentTempData: ''
    },
    watch: {
      merchantIdProp(val) {
        if(val){
          this.page = 1;
          this.searchText = '';
          this.isShop = '';
          this.classifyId = ''
          this.childClassifyId = ''
          this.merchantId = val
          this.getGoodsList()
        }
      },
      merchantId(value) {
        this.classifyId = ''
        if(value){
          this.getGoodsClassifyList(value)
        }
      },
      classifyId(value) {
        this.childClassifyId = ''
        this.getGoodsClassifyList(this.merchantId,value)
      },
      componentTempData(value){
        this.changeDataByWatch(value)
      }
    },
    data() {
      return {
        page: 1,
        limit: 6,
        searchText: '',
        tableLoadingShow: false,
        tableData: [],
        pageTotal: 0,
        merchantId: 1,
        classifyId: '',
        merchantList: [],
        childClassifyId: '',
        classifyList: [],
        classifyListSecond: [],
        selectedIds: [],
        selectedDetails: []
      }
    },
    mounted() {
      this.changeDataByWatch(this.componentTempData)
      this.getMerchantList()
      this.getGoodsClassifyList(1)
      this.getGoodsList()

    },
    methods: {


      changeDataByWatch(value) {
        if (!value || value.length == 0) {
          return
        }

        this.selectedDetails = value.map((item, index) => {
          return item
        })
        this.getGoodsList()
      },

      confirmSelectData() {
        this.$emit('hideModelMsgDialog',this.selectedDetails)
      },

      searchData() {
        this.page = 1
        this.getGoodsList()
      },

      async getGoodsList() {
        this.tableLoadingShow = true
        let params = {
          page: this.page,
          limit: this.limit,
          merchant_id: 1,
          keyword: this.searchText,
          classify_id: this.childClassifyId?this.childClassifyId:this.classifyId
        }
        const res = await this.$api.getGoodsList(params)
        if(res.data.level=="success"){
          this.tableData = res.data.data
          this.pageTotal = res.data.page_info.total
          /*this.toggleSelection()*/
          this.$nextTick(() => {
            this.echo()
          })
        }
        this.tableLoadingShow = false
      },

      inputClear() {

      },

      //店家复选框框的事件
      handleSelectionChange(item,type,index) {
        item.hasSelected = type
        if(type){
          this.selectedIds.push(item.id)
          this.selectedDetails.push({
            id: item.id,
            upc: item.upc,
            thumb_url: item.thumb_url,
            name: item.name,
          })
        } else {
          /*let index = this.selectedIds.indexOf(item.id)*/
          this.selectedIds.splice(index,1)
          this.selectedDetails.splice(index,1)
        }
        this.$set(this.tableData, index, item)
      },

      //获取门店的分类
      async getGoodsClassifyList(id,pid){
        let params = {
          limit:100,
          page:1,
          merchant_id: id,
          pid: pid?pid:''
        }
        const res = await this.$api.getGoodsClassifyList(params);
        if(res.data.level=='success'){
          let list = res.data.data;
          if(!pid){
            this.classifyList = res.data.data
            this.classifyList = []
            this.classifyList.push({id: 0,name: '无分类'})
            list.forEach((item,index) => {
              this.classifyList.push(item)
            })
          } else{
            this.classifyListSecond = res.data.data
          }
        }else{
          this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      },

      //初始化表格复选框状态
      toggleSelection() {
        this.tableData.forEach((item,index) => {
          let result = this.selectedDetails.find(s => s.id == item.id)
          if(result){
            item.hasSelected = true
          } else {
            item.hasSelected = ''
          }
        })
      },

      //分页
      pageChange(e) {
        this.page = e;
        this.getGoodsList();
      },

      resetSearch(){
        this.page = 1;
        this.searchText = '';
        this.merchantId = '';
        this.isShop = '';
        this.classifyId = ''
        this.childClassifyId = ''
        this.getGoodsList()
      },

      merchantSelectClear() {
        this.page = 1
        this.classifyId = ''
        this.childClassifyId = ''
        this.classifyListSecond = ''
        this.classifyList = []
        this.classifyListSecond = []
        this.getGoodsList()
      },

      //获取门店列表
      async getMerchantList(){
        let params = {
          limit:50,
          page:1
        }
        const res = await this.$api.getMerchantList(params);
        if(res.data.level=='success'){
          let list = res.data.data;
          this.merchantList = list;
        }else{
          this.$message({
            message: res.data.message,
            type: 'warning'
          });
        }
      },

      classifySelectClear() {
        this.page = 1
        this.childClassifyId = ''
        this.getGoodsList()
      },

      selectClear() {
        this.page = 1
        this.getGoodsList()
      },


      /**
       * 回显操作
       */

      handleSelect(selection, row) {
        // isExited判断selected是否已经存在当前项
        let isExited = false
        console.log('没有执行吗')
        console.log('Kankanzheli',this.selectedDetails)
        this.selectedDetails.forEach(item => {
          if (item.id == row.id) {
            isExited = true
          }
        })
        if (isExited) {
          // 若存在，代表操作是 取消选中
          this.handleDelItem(row)
        } else {
          // 反之，选中某项
          this.selectedDetails.push(row)
        }
      },

      /**
       * @description: 全选 or 全不选
       * @param selection 选中数据
       */
      handleSelectionAll(selection) {
        if (selection.length == 0) {
          // 若是全不选，则循环删除selected数组中存在的项
          this.tableData.forEach(item => {
            this.handleDelItem(item)
          })
        } else {
          // 全选，将selected和当前table数据合起来，注意去重！
          // this.selected = this.unique(
          //   this.selected.concat(this.curTableData)
          // )
          //TODO  没必要先把已经存好的去掉，再拼接表格数据，判断没有选中的把它加进去就行了
          let tempData = []
          this.tableData.forEach(item => {
            let index = -1
            this.selectedDetails.forEach((item2, idx) => {
              if (item2.id == item.id) {
                index = idx
              }
            })
            if (index == -1) {
              tempData.push(item)
            }
          })
          this.selectedDetails = this.selectedDetails.concat(tempData)
        }
      },

      /**
       * @description: 删除selected数组中某项数据
       * @param row 行数据
       */
      handleDelItem(row) {
        let index = -1
        this.selectedDetails.forEach((item, idx) => {
          if (item.id == row.id) {
            index = idx
          }
        })
        if (index >= 0) {
          this.selectedDetails.splice(index, 1)
        }
      },

      // 当前页面切换触发回显
      handleCurrentChange() {
        this.echo()
      },

      // 回显
      echo() {
        let rows = []
        this.tableData.forEach(row => {
          this.selectedDetails.forEach(item => {
            if (row.id == item.id) {
              rows.push(row)
            }
          })
        })
        this.toggleSelectionByNew(rows)
      },

      // el-table自带方法
      toggleSelectionByNew(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.dataList.toggleRowSelection(row);
          });
        } else {
          this.$refs.dataList.clearSelection();
        }
      }


    },
  }
</script>

<style scoped lang="scss">
  .page-code{
    margin-top: 15px;
  }
  .action-bar{
    background-color: #f2f2f2;
    height: 60px;
    margin: 10px 0px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 20px;
  }
</style>

<style scoped>
  /deep/.el-table td, /deep/.el-table th {
    text-align: center;
  }
  /deep/.el-table .warning-row {
    background: #f8f9fa;
  }

  /deep/.el-table .success-row {
    background: #ffffff;
  }
  /deep/.el_table_style{
    border: 1px solid #dee2e6;
  }
  /deep/.el-table td {
    border: none;
  }
</style>
